from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.database import get_db
from app.core.deps import get_current_user, get_tenant_id
from app.models.user import User
from app.schemas.user import (
    ChangePasswordRequest,
    UpdateProfileRequest,
    UserForm,
    UserQuery,
)
from app.services.user import user_service
from app.utils.response import ResponseUtil

router = APIRouter()


@router.get("/list", summary="查询用户列表")
async def list_users(
    query: UserQuery = Depends(),
    db: AsyncSession = Depends(get_db),
    tenant_id: str = Depends(get_tenant_id),
):
    """查询用户列表 - Plus-UI兼容接口"""
    try:
        users = await user_service.get_user_list(
            db=db, query=query, tenant_id=tenant_id
        )
        return ResponseUtil.success(data=users)
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"查询用户列表失败: {str(e)}",
        )


@router.get("/{user_id}", summary="获取用户详情")
async def get_user(
    user_id: int,
    db: AsyncSession = Depends(get_db),
    tenant_id: str = Depends(get_tenant_id),
):
    """根据ID获取用户详情 - Plus-UI兼容接口"""
    try:
        if user_id == 0:
            # 新增用户时的空ID，返回空的用户信息用于表单初始化
            return ResponseUtil.success(
                data={
                    "user": None,
                    "roles": [],
                    "roleIds": [],
                    "posts": [],
                    "postIds": [],
                    "roleGroup": "",
                    "postGroup": "",
                }
            )

        user_info = await user_service.get_user_info(
            db=db, user_id=user_id, tenant_id=tenant_id
        )

        if not user_info:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")

        return ResponseUtil.success(data=user_info)
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取用户详情失败: {str(e)}",
        )


@router.post("", summary="新增用户")
async def add_user(
    data: UserForm,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id),
):
    """新增用户 - Plus-UI兼容接口"""
    try:
        # 检查用户名是否已存在
        existing_user = await user_service.get_by_username(
            db, username=data.userName, tenant_id=tenant_id
        )
        if existing_user:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST, detail="用户名已存在"
            )

        # 创建用户
        new_user = await user_service.create_user(
            db=db, user_data=data, tenant_id=tenant_id, creator_id=current_user.user_id
        )

        return ResponseUtil.success(data={"userId": new_user.user_id}, message="用户创建成功")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"创建用户失败: {str(e)}",
        )


@router.put("", summary="修改用户")
async def update_user(
    data: UserForm,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id),
):
    """修改用户 - Plus-UI兼容接口"""
    try:
        if not data.userId:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST, detail="用户ID不能为空"
            )

        # 更新用户
        updated_user = await user_service.update_user(
            db=db,
            user_id=int(data.userId),
            user_data=data,
            tenant_id=tenant_id,
            updater_id=current_user.user_id,
        )

        if not updated_user:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")

        return ResponseUtil.success(message="用户更新成功")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"更新用户失败: {str(e)}",
        )


@router.delete("/{user_id}", summary="删除用户")
async def del_user(
    user_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id),
):
    """删除用户 - Plus-UI兼容接口"""
    try:
        # 检查是否为当前用户自己
        if user_id == current_user.user_id:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST, detail="不能删除当前登录用户"
            )

        # 删除用户（软删除）
        success = await user_service.delete_user(
            db=db, user_id=user_id, tenant_id=tenant_id
        )

        if not success:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")

        return ResponseUtil.success(message="用户删除成功")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"删除用户失败: {str(e)}",
        )


@router.put("/resetPwd", summary="重置用户密码")
async def reset_user_pwd(
    data: dict,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id),
):
    """重置用户密码 - Plus-UI兼容接口"""
    try:
        user_id = data.get("userId")
        password = data.get("password")

        if not user_id or not password:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST, detail="用户ID和密码不能为空"
            )

        await user_service.reset_password(
            db=db, user_id=user_id, password=password, tenant_id=tenant_id
        )

        return ResponseUtil.success(message="密码重置成功")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"重置密码失败: {str(e)}",
        )


@router.put("/changeStatus", summary="修改用户状态")
async def change_user_status(
    data: dict,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id),
):
    """修改用户状态 - Plus-UI兼容接口"""
    try:
        user_id = data.get("userId")
        status_value = data.get("status")

        if user_id is None or status_value is None:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST, detail="用户ID和状态不能为空"
            )

        if user_id == current_user.user_id:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST, detail="不能修改当前登录用户的状态"
            )

        await user_service.change_status(
            db=db, user_id=user_id, status=status_value, tenant_id=tenant_id
        )

        return ResponseUtil.success(message="状态修改成功")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"修改状态失败: {str(e)}",
        )


@router.get("/profile", summary="获取个人信息")
async def get_profile(
    current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
):
    """获取个人信息 - Plus-UI兼容接口"""
    try:
        user_info = await user_service.get_user_info(
            db=db, user_id=current_user.user_id, tenant_id=current_user.tenant_id
        )
        return ResponseUtil.success(data=user_info)
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取个人信息失败: {str(e)}",
        )


@router.put("/profile", summary="修改个人信息")
async def update_profile(
    data: UpdateProfileRequest,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    """修改个人信息 - Plus-UI兼容接口"""
    try:
        await user_service.update_profile(
            db=db, user_id=current_user.user_id, profile_data=data
        )
        return ResponseUtil.success(message="个人信息修改成功")
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"修改个人信息失败: {str(e)}",
        )


@router.put("/profile/updatePwd", summary="修改个人密码")
async def update_pwd(
    data: ChangePasswordRequest,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    """修改个人密码 - Plus-UI兼容接口"""
    try:
        await user_service.change_password(
            db=db,
            user_id=current_user.user_id,
            old_password=data.oldPassword,
            new_password=data.newPassword,
        )
        return ResponseUtil.success(message="密码修改成功")
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"修改密码失败: {str(e)}",
        )


@router.get("/authRole/{user_id}", summary="查询授权角色")
async def get_auth_role(
    user_id: int,
    db: AsyncSession = Depends(get_db),
    tenant_id: str = Depends(get_tenant_id),
):
    """查询授权角色 - Plus-UI兼容接口"""
    try:
        auth_info = await user_service.get_auth_role(
            db=db, user_id=user_id, tenant_id=tenant_id
        )
        return ResponseUtil.success(data=auth_info)
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"查询授权角色失败: {str(e)}",
        )


@router.put("/authRole", summary="保存授权角色")
async def update_auth_role(
    userId: str = Query(...),
    roleIds: str = Query(...),
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id),
):
    """保存授权角色 - Plus-UI兼容接口"""
    try:
        role_id_list = [int(rid.strip()) for rid in roleIds.split(",") if rid.strip()]
        await user_service.update_user_roles(
            db=db, user_id=int(userId), role_ids=role_id_list, tenant_id=tenant_id
        )
        return ResponseUtil.success(message="角色授权成功")
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"角色授权失败: {str(e)}",
        )


@router.get("/getInfo", summary="获取用户详细信息")
async def get_info(
    current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
):
    """获取用户详细信息 - Plus-UI兼容接口"""
    try:
        user_info = await user_service.get_current_user_info(db=db, user=current_user)
        return ResponseUtil.success(data=user_info)
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取用户信息失败: {str(e)}",
        )
